<template>
  <el-card class="order-container">
    <template #header>
      <div class="header">
        <el-input
          style="width: 200px; margin-right: 10px"
          placeholder="预约人名称关键字"
          v-model="state.userName"
          @change="handleOption"
          clearable
        />
        <el-button type="success" color="#71c4ef" @click="handleSearch">查询</el-button>
        <el-button type="success" color="#313d44" plain @click="handleReset">重置</el-button>
      </div>
    </template>
    <template #reference>
      <el-button type="danger" :icon="Delete">批量删除</el-button>
    </template>
    <!-- 将 load 改为 loading -->
    <el-table
      :loading="state.loading"
      :data="state.tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
      ></el-table-column>
      <el-table-column
        label="序号"
        align="center"
        width="60"
      >
        <template #default="scope">
          {{ (state.currentPage - 1) * state.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="serviceId"
        label="服务ID"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="serviceName"
        label="服务名称"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="userName"
        label="预约人"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="reservationTime"
        label="预约时间"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column
          prop="emergencyContactPhone"
          label="紧急联系电话"
          width="110"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="serviceAddress"
          label="预约地址"
          align="center"
      ></el-table-column>
      <el-table-column
        label="审核状态"
        align="center"
      >
        <template #default="scope">
          <el-tag
            :type="getTagType(scope.row.reviewStatus)">
            {{ reviewStatusMap[scope.row.reviewStatus] || '未审核' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="reviewOpinion"
        label="审核意见"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <div class="checkup">
            
              <el-button type="warning" size="small" style="margin-left: 8px" :disabled="scope.row.id === '1'"
              @click="handleReview(scope.row)">审核</el-button>
          
            
              <el-button type="danger" size="small" style="margin-left: 8px"  :disabled="scope.row.id === '1'"
              @click="handleDelete(scope.row.id)">删除</el-button>
            
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="state.total"
      :page-size="state.pageSize"
      :current-page="state.currentPage"
      @current-change="changePage"
    />
    <!-- 审核弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="审核"
      width="30%"
      @close="resetReviewForm"
    >
      <!-- <template #content> -->
      <div class="review-form">
        <el-radio-group v-model="selectedReviewStatus" class="review-status-group">
          <el-radio :value="1">审核通过</el-radio>
          <el-radio :value="2">审核拒绝</el-radio>
        </el-radio-group>
        <el-input
          v-model="reviewOpinion"
          placeholder="请输入审核意见"
          type="textarea"
          :rows="3"
          style="margin-top: 10px"
        />
      </div>
      <!-- </template> -->
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReview">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import 'element-plus/dist/index.css';
import { onMounted, reactive, ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { HomeFilled, Delete } from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'; // 引入样式文件
import {
  deleteServiceReservationById,
  getServiceReservationById,
  reviewServiceReservation,
  listServiceReservations
} from '../../service/serviceReservationApi'



const state = reactive({
  loading: false,
  tableData: [], // 数据列表
  multipleSelection: [], // 选中项
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  serviceId: '', // 订单号
  reviewStatus: '', // 订单状态
  userName: '', // 预约人姓名
  // serviceName: '', // 服务名称
  // 订单状态筛选项默认值
})

// 审核弹窗相关
const dialogVisible = ref(false);
const selectedReviewStatus = ref(1); // 默认审核通过
const reviewOpinion = ref(''); // 审核意见
const currentReviewRow = ref(null); // 当前审核的行数据

// 审核状态映射
const reviewStatusMap = {
  1: '审核通过',
  2: '审核拒绝'
}

// 根据审核状态返回标签类型
const getTagType = (status) => {
  if (status === 1) {
    return 'success'; // 绿色
  } else if (status === 2) {
    return 'danger'; // 红色
  }
  return 'info'; // 默认灰色
};

// 打开审核弹窗
const handleReview = (row) => {
  currentReviewRow.value = row;
  dialogVisible.value = true;
};

// 提交审核
const submitReview = async () => {
  if (!reviewOpinion.value.trim()) {
    ElMessage.error('审核意见不能为空');
    return;
  }

  const reviewDTO = {
    id: currentReviewRow.value.id,
    reviewOpinion: reviewOpinion.value,
    reviewStatus: selectedReviewStatus.value,
  };

  try {
    const response = await reviewServiceReservation(reviewDTO); 
    await reviewServiceReservation(reviewDTO);
    let statusText = '';
    if (selectedReviewStatus.value === 1) {
      statusText = '审核通过';
    } else {
      statusText = '审核拒绝';
    }
    ElMessage.success(`${statusText}成功`);
    dialogVisible.value = false;
    getOrderList();
  } catch (error) {
    let statusText = '';
    if (selectedReviewStatus.value === 1) {
      statusText = '审核通过';
      
    } else {
      statusText = '审核拒绝';
    }
    ElMessage.error(`${statusText}失败`);
    console.error('审核失败:', error);
  }
};

// 关闭审核弹窗时重置表单
const resetReviewForm = () => {
  selectedReviewStatus.value = 1;
  reviewOpinion.value = '';
  currentReviewRow.value = null;
};

// 初始化获取订单列表
onMounted(() => {
  getOrderList()
})

// 获取列表方法
const getOrderList = async () => {
  state.loading = true
  const params = {
    pageNum: state.currentPage,
    pageSize: state.pageSize,
    reviewStatus: state.reviewStatus,
    serviceName: state.serviceName,
    userName: state.userName
  }

  try {
    const response = await listServiceReservations(params)
    if (response && response.data) {
      state.tableData = response.data.records || [];
      state.total = response.data.total || 0;
    } else {
      ElMessage.error('获取订单列表失败：服务器返回数据为空');
      state.tableData = [];
      state.total = 0;
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败')
    console.error('获取订单列表失败:', error)
  } finally {
    state.loading = false
  }
}

// 搜索处理
const handleSearch = () => {
  state.currentPage = 1
  getOrderList()
}

// 重置处理
const handleReset = () => {
  // 重置所有查询条件
  state.userName = ''
  state.reviewStatus = ''
  state.serviceName = ''
  state.serviceId = ''
  state.currentPage = 1 // 重置当前页码为第一页
  getOrderList()
}

// 触发过滤项方法
const handleOption = () => {
  state.currentPage = 1
  getOrderList()
}

// checkbox 选择项
const handleSelectionChange = (val) => {
  state.multipleSelection = val
}

// 翻页方法
const changePage = (val) => {
  state.currentPage = val
  getOrderList()
}

// 删除方法
const handleDelete = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteServiceReservationById(orderId)
    ElMessage.success('删除成功')
    getOrderList()
  } catch (error) {
    // 用户取消删除
    if (error === 'cancel') {
      return
    }
    ElMessage.error('删除失败')
    console.error('删除失败:', error)
  }
}
</script>